package com.lyl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lyl.domain.SysMenu;
import com.lyl.domain.SysPrivilege;
import com.lyl.domain.SysRolePrivilege;
import com.lyl.mapper.SysMenuMapper;
import com.lyl.mapper.SysRolePrivilegeMapper;
import com.lyl.model.RolePrivilegeParam;
import com.lyl.service.SysMenuService;
import com.lyl.service.SysPrivilegeService;
import com.lyl.service.SysRolePrivilegeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author lylbell
 * @date 2021-06-22 13:31
 */
    
@Service
public class SysRolePrivilegeServiceImpl extends ServiceImpl<SysRolePrivilegeMapper, SysRolePrivilege> implements SysRolePrivilegeService {


    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysPrivilegeService sysPrivilegeService;

    @Autowired
    private SysRolePrivilegeService sysRolePrivilegeService;

    /**
     * 通过角色id查询菜单权限
     * @param roleId
     * @return
     */
    @Override
    public List<SysMenu> findMenuAndPrivilegeByRoleId(Long roleId) {
        //1、获取二级菜单，并将childs和privileges填充（递归调用）
        List<SysMenu> list = sysMenuService.list(); //（1）获取所有的菜单
        if (CollectionUtils.isEmpty(list)) {   //为空情况处理
            return Collections.emptyList();
        }
        //（2）获取所有一级菜单（作用：在获取二级菜单的时候，过滤掉）
        List<SysMenu> menuParents = list.stream().filter(sysMenu -> sysMenu.getParentId() == null).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(menuParents)) {
            return Collections.emptyList();
        }

        //（3）获取二级菜单
        List<SysMenu> menuChilds = new ArrayList<>();
        for (SysMenu menuParent : menuParents) {
            menuChilds.addAll(getMenuChilds(menuParent.getId(),roleId,list));
        }

        //2、通过角色id查获取的权限
        return menuChilds;
    }



    /**
     * 递归获取二级菜单
     * @param parentId
     * @param roleId
     * @param menus  所有的菜单
     * @return
     */
    private List<SysMenu> getMenuChilds(Long parentId, Long roleId, List<SysMenu> menus) {
        List<SysMenu> menuChilds = new ArrayList<>();
        for (SysMenu menu : menus) {
            if (menu.getParentId() == parentId) {  //找孩子
                //1、递归调用，获取孩子的孩子
                menu.setChilds(getMenuChilds(menu.getId(), roleId, menus));
                //2、获取菜单下对应的所有权限，并把该角色拥有的的权限也放入（own字段设置为1）
                List<SysPrivilege> sysPrivileges = sysPrivilegeService.findAllSysPrivilege(menu.getId(),roleId);
                menu.setPrivileges(sysPrivileges);
                menuChilds.add(menu);//最后放入
            }
        }
        return menuChilds;
    }


    /**
     * 给角色授权
     * @param rolePrivilegeParam
     * @return
     */
    @Transactional
    @Override
    public Boolean grantPrivilege(RolePrivilegeParam rolePrivilegeParam) {
        Long roleId = rolePrivilegeParam.getRoleId();
        //1、先删除原有的角色对应的权限数据
        sysRolePrivilegeService.remove(new LambdaQueryWrapper<SysRolePrivilege>().eq(SysRolePrivilege::getRoleId,roleId));

        //2、再重新添加到角色权限表中
        List<Long> privilegeIds = rolePrivilegeParam.getPrivilegeIds();
        if (CollectionUtils.isEmpty(privilegeIds)) {
            return false;
        }
        List<SysRolePrivilege> sysRolePrivileges = new ArrayList<>();
        for (Long privilegeId : privilegeIds) {
            SysRolePrivilege sysRolePrivilege = new SysRolePrivilege();
            sysRolePrivilege.setPrivilegeId(privilegeId);
            sysRolePrivilege.setRoleId(roleId);
            sysRolePrivileges.add(sysRolePrivilege);
        }
        return sysRolePrivilegeService.saveBatch(sysRolePrivileges);
    }
}
